<template>
    <div>
        <!-- 面包屑 -->
        <border-header second="权限管理" third="角色管理"></border-header>

        <el-card>
            <el-button type="primary" @click="addRoleVisible=true">添加角色</el-button>

            <el-table :data="roleList" style="width: 100%" stripe border>
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bdbottom',i1===0?'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
                            <!-- 一级权限 -->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{ item1.authName }}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 二级与三级权限 -->
                            <el-col :span="19">
                                <el-row :class="[i2===0?'':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                                    <!-- 二级 -->
                                    <el-col :span="6">
                                        <el-tag closable @close="removeRightById(scope.row,item2.id)" type="success">{{ item2.authName }}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <!-- 三级 -->
                                    <el-col :span="18">
                                        <el-tag closable @close="removeRightById(scope.row,item3.id)" type="warning" v-for="item3 in item2.children" :key="item3.id">{{ item3.authName }}</el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditRole(scope.row.id)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeEditRole(scope.row.id)">删除</el-button>
                        <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 添加角色的对话框 -->
        <el-dialog title="添加角色" :visible.sync="addRoleVisible" width="50%" @close="addRoleClosed">
            <el-form :model="addForm" :rules="addRole" ref="addRoleRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addRoleVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRose">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑角色的对话框 -->
        <el-dialog title="编辑角色" :visible.sync="editRoleVisible" width="50%" @close="addRoleClosed">
            <el-form :model="editForm" :rules="addRole" ref="addRoleRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editRoleVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRose">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配角色的对话框 -->
        <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">
            <!-- 树形控件 -->
            <el-tree ref="treeRef" :data="rolesList" :props="treeProps" show-checkbox default-expand-all node-key="id" :default-checked-keys="defKeys"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import BorderHeader from '../BorderHeader.vue'
import http from '@/util/http'
export default {
  data () {
    return {
      roleList: [],
      // 添加角色对话框的显示和隐藏
      addRoleVisible: false,
      // 添加角色的内容
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色内容的验证规则
      addRole: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      },

      // 编辑角色对话框的显示与隐藏
      editRoleVisible: false,
      // 编辑角色的内容
      editForm: {},
      // 分配权限的对话框的显示与隐藏
      setRightDialogVisible: false,
      // 用户所有的权限列表
      rolesList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的id值数组
      defKeys: [],
      // 当前选中角色的id值
      roleId: ''
    }
  },
  components: {
    BorderHeader
  },
  created () {
    this.getRoleList()
  },
  methods: {
    async getRoleList () {
      const { data: res } = await http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.roleList = res.data
    },
    // 添加角色对话框关闭所对应的事件
    addRoleClosed () {
      this.$refs.addRoleRef.resetFields()
    },
    // 添加角色对话框的确定点击事件
    addRose () {
      this.$refs.addRoleRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await http.post('roles', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加角色失败')
        }
        // 隐藏对话框
        this.addRoleVisible = false
        // 刷新
        this.getRoleList()
        this.$message.success('添加用户成功')
      })
    },
    // 编辑角色的点击事件
    async showEditRole (id) {
      const { data: res } = await http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('获取角色信息失败')
      this.editForm = res.data
      this.editRoleVisible = true
    },
    // 编辑角色对话框的确定点击事件
    editRose () {
      this.$refs.addRoleRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await http.put('roles/' + this.editForm.roleId, { roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc })
        if (res.meta.status !== 200) {
          this.$message.error('编辑角色失败')
        }
        // 隐藏对话框
        this.editRoleVisible = false
        // 刷新
        this.getRoleList()
        this.$message.success('编辑用户成功')
      })
    },

    // 删除角色
    async removeEditRole (id) {
      // 弹框询问是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      this.getRoleList()
    },
    // 根据id删除角色的权限
    async removeRightById (role, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      // 返回的data，是当前角色最新的权限，直接更新会造成页面的整体渲染
      role.children = res.data
      this.$message.success('删除权限成功')
    },

    // 展示分配权限的对话框
    async showSetRightDialog (roles) {
      // 把当前角色的id保存在data中
      this.roleId = roles.id

      const { data: res } = await http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
      this.rolesList = res.data

      // 递归获取所有的三级节点
      this.getLeafKeys(roles, this.defKeys)

      this.setRightDialogVisible = true
    },

    // 通过递归的方式，获取角色下所有三级权限的id，并保存到数组中
    getLeafKeys (node, arr) {
      // 如果当前node没有children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },

    // 监听分配权限对话框关闭的事件
    setRightDialogClosed () {
      this.defKeys = []
    },
    // 分配权限点击确定的事件
    async allotRights () {
      // 获取所有被选中、叶子节点的key和半选中节点的key
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')
      const { data: res } = await http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')
      this.$message.success('分配权限成功')
      this.getRoleList()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag{
    margin: 7px;
}

.bdtop{
    border-top: 1px solid #eee;
}

.bdbottom{
    border-bottom: 1px solid #eee;
}

.vcenter{
    display: flex;
    align-items: center;
}
.el-table .el-table__cell {
    text-align: center;
}
</style>
